<template>
  <div class="con">
    <div class="contbox6_10">
      <p class="titlelist6_10 titlser">
        商城管理
        <span style="color: #999">&nbsp;&nbsp;/&nbsp;&nbsp;</span>入库
      </p>
      <div class="content">
        <div class="jibenInfo">商品信息</div>
        <div class="sousuojg6_10">
          <el-form :model="formInline" class="demo-form-inline">
            <el-form-item label="品牌名称" label-width="120px">
              <el-select
                v-model="formInline.channelName"
                @change="productList"
                clearable
                placeholder="请选择"
                :disabled="disableds"
              >
                <el-option
                  v-for="(item, i) in NameList"
                  :key="'a' + i"
                  :label="item.channelName"
                  :value="item.uid"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品类型" label-width="120px">
              <el-cascader
                :disabled="disableds"
                v-model="formInline.channelType"
                :options="options"
                :props="{ emitPath: false }"
                @change="productList"
              ></el-cascader>
            </el-form-item>
            <el-col>
              <el-form-item label="商品名称" label-width="120px">
                <el-select
                  :disabled="disableds"
                  v-model="formInline.productUid"
                  @change="shoopChange"
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in productListData"
                    :key="'c' + i"
                    :label="item.productName"
                    :value="item.productUid"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="商品型号"
                v-if="formInline.productUid != ''"
                label-width="120px"
              >
                <el-input
                  v-model="shopType"
                  disabled
                  placeholder="请输入内容"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- <div class="jibenInfo">
              限制条件<span
                >（选填项，输入则按照数值限制；不输入则不做限制）</span
              >
            </div> -->
            <!-- <el-form-item label="最少购买数量" label-width="120px">
              <el-input
                style="width: 300px"
                @input="value=>{formInline.saleMinCnt=value.replace(/[^\d]+/g,'')}"
                :maxlength="2"
                v-model="formInline.saleMinCnt"
                placeholder="请输入最少购买数量"
              ></el-input>
            </el-form-item>
            <el-form-item label="最多购买数量" label-width="120px">
              <el-input
                style="width: 300px"
                :maxlength="9"
                v-model="formInline.saleMaxCnt"
                @input="value=>{formInline.saleMaxCnt=value.replace(/[^\d]+/g,'')}"
                placeholder="请输入最多购买数量"
              ></el-input>
            </el-form-item> -->
            <p class="shopList"></p>
            <div style="clear: both; height: 30px"></div>
            <div style="margin-bottom: 20px; margin-left: 50px">
              <el-radio v-model="radio" :disabled="radioBool" label="1"
                >起始号段录入</el-radio
              >
              <el-radio v-model="radio" :disabled="radioBool" label="2"
                >批量上传录入</el-radio
              >
            </div>
            <!-- <div class="jibenInfo">商品序列号（SN）录入</div> -->
            <el-col v-if="radio == 1">
              <el-form-item label="起始号段" label-width="120px">
                <el-input
                  style="width: 300px"
                  :maxlength="60"
                  @input="
                    (value) => {
                      formInline.startSn = value.replace(/[\W]/g, '');
                    }
                  "
                  v-model="formInline.startSn"
                  placeholder="请输入产品起始号段"
                ></el-input>
              </el-form-item>
              <el-form-item label="新增数量" label-width="120px">
                <el-input
                  maxlength="3"
                  style="width: 300px"
                  v-model="formInline.snNum"
                  @input="
                    (vlaue) => {
                      formInline.snNum = value.replace(/[^\d]+/g, '');
                    }
                  "
                  placeholder="请输入本次录入数量,一次最多录入999台"
                ></el-input>

                <span style="color: #409eff; cursor: pointer" @click="preview"
                  >预览</span
                >
              </el-form-item>
            </el-col>

            <el-col v-if="radio == 2" style="margin-left: 30px">
              <el-button
                style="
                  margin-right: 10px;
                  float: left;
                  margin-left: 20px;
                  color: #409eff;
                "
                @click="excal"
                >下载模版</el-button
              >
              <span
                ><el-upload
                  class="upload-demo"
                  style="float: left; color: #409eff"
                  action
                  ref="upload"
                  :http-request="submitFileSave"
                  :before-upload="beforeAvatarUpload"
                  :show-file-list="false"
                >
                  <el-button style="color: #409eff" type="" icon="edit"
                    >批量上传</el-button
                  >
                </el-upload>
              </span>
              <div style="display: flex; align-items: center" v-if="uploadBool">
                <div style="margin-right: 20px; margin-left: 20px">
                  上传结果
                </div>
                <div style="margin-right: 20px">总数：{{ totalNumber }}</div>
                <div style="margin-right: 20px">成功：{{ successNumber }}</div>
                <div style="margin-right: 20px">失败：{{ finalNumber }}</div>
                <el-button type="text" @click="seeSucs">预览</el-button>
              </div>
            </el-col>
          </el-form>
        </div>
        <div style="height: 30px; clear: both"></div>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :disabled="disabled"
            style="margin-left: 40%"
            @click="fromData"
            >确 定</el-button
          >
          <el-button @click="handleCloses">取 消</el-button>
        </span>
      </div>
      <el-dialog title="上传结果" :visible.sync="dialogVisible2" width="30%">
        <!-- <span>完成入库（详情可在库存明细查询）</span> -->
        <div style="margin-top: 20px">
          <span>总数 {{ totalNumber }}</span>
          <span>成功 {{ successNumber }}</span>
          <span>失败 {{ finalNumber }}</span>
        </div>
        <div class="statusBox" style="background:#f4f7fa">
          <div style="text-align:center;padding:10px 0;" v-if="resSuccess.length > 0">成功</div>
          <div style="text-align:center;padding:10px 0;" v-if="resFail.length > 0">失败</div>
        </div>
        <div class="statusBox" style="border-right:1px solid #f4f7fa">
          <div class="successArr" v-if="resSuccess.length > 0">
            <!-- <div
              style="
                border-bottom: 1px solid #ebeef5;
                padding: 10px 0;
                background: #f4f7fa;
              "
              class="statusName"
            >
              成功
            </div> -->
            <div
              v-for="(item, index) in resSuccess"
              style="padding: 10px 0"
              class="statusList"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
          <div class="failArr" v-if="resFail.length > 0">
            <!-- <div
              style="
                border-bottom: 1px solid #ebeef5;
                padding: 10px 0;
                background: #f4f7fa;
              "
              class="statusName"
            >
              失败
            </div> -->
            <div
              v-for="(item, index) in resFail"
              style="padding: 10px 0"
              class="statusList"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible2 = false"
            >确认</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        title="入库中，请勿离开操作页面…"
        :visible.sync="dialogVisible1"
        width="30%"
      >
        <span>商品入库中…</span>
      </el-dialog>
      <el-dialog
        title="SN序列号详情"
        class="xulie"
        :visible.sync="dialogVisible"
        width="40%"
        append-to-body
        :before-close="handleClose"
      >
        <!-- 这里是加出来的数字 -->
        <div style="height: 350px">
          <el-table
            :data="formInline.sns"
            border
            height="320"
            :row-style="{ height: '0px' }"
            :cell-style="{ padding: '0px' }"
            :header-cell-style="{ background: '#DCDCDC', color: '#222' }"
          >
            <el-table-column
              prop="sn"
              align="center"
              label="SN"
            ></el-table-column>
          </el-table>
        </div>
      </el-dialog>
      <el-dialog
        title="预览"
        :visible.sync="dialogVisible4"
        width="30%"
        :before-close="handleClosep"
      >
        <div style="margin-bottom: 20px">
          <span>总数 {{ totalNumber }}</span>
          <span>成功 {{ successNumber }}</span>
          <span>失败 {{ finalNumber }}</span>
        </div>
        <div class="statusBox" style="background:#f4f7fa">
          <div style="text-align:center;padding:10px 0;" v-if="resSuccess.length > 0">成功</div>
          <div style="text-align:center;padding:10px 0;" v-if="resFail.length > 0">失败</div>
        </div>
        <div class="statusBox borderBox">
          <div class="successArr" v-if="resSuccess.length > 0">
            <!-- <div
              style="
                border-bottom: 1px solid #ebeef5;
                padding: 10px 0;
                background: #f4f7fa;
              "
              class="statusName"
            >
              成功
            </div> -->
            <div
              v-for="(item, index) in resSuccess"
              style="padding: 10px 0"
              class="statusList"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
          <div class="failArr" v-if="resFail.length > 0">
            <!-- <div
              style="
                border-bottom: 1px solid #ebeef5;
                padding: 10px 0;
                background: #f4f7fa;
              "
              class="statusName"
            >
              失败
            </div> -->
            <div
              v-for="(item, index) in resFail"
              style="padding: 10px 0"
              class="statusList"
              :key="index"
            >
              {{ item }}
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogVisible4 = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible4 = false"
            >确 定</el-button
          > -->
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import bus from "../../assets/js/bus";
import axios from "axios";
import https from "../../plugins/https.js";
import { sumBigNumber } from "../../assets/js/commion";
import qs from "qs";
// 批量导出
import { exportFile } from "../../plugins/expord";
export default {
  data() {
    return {
      // 上传结果
      uploadBool: false,
      radio: "1",
      dialogVisible4: false,
      disabled: false,
      disableds: false,
      totalNumber: "",
      successNumber: "",
      finalNumber: "",
      dialogVisible1: false,
      dialogVisible2: false,
      fileData: new FormData(), //文件上传对象
      NameList: [],
      BrandTypeList: [],
      productListData: [],
      options: [],
      channelTypeLists: [],
      channelTypeList: [],
      dialogVisible: false,
      previewType: true,
      shopType: "",
      radioBool: false,
      formInline: {
        oemUid: localStorage.getItem("uid"), //OEMid
        channelUid: "",
        BrandType: "",
        productUid: "",
        saleMaxCnt: "",
        saleMinCnt: "1",
        startSn: "",
        snNum: "",
        sns: [],
      },
      zeroNum: "",
      tableData: [
        { name: 123, status: 0 },
        { name: 123, status: 1 },
      ],
      resSuccess: [1, 2, 3, 4,1, 2, 3, 4,1, 2, 3, 4,1, 2, 3, 4], //存放成功的
      resFail: [5, 6, 7, 8], //存放失败的
    };
  },
  created() {
    if (this.$route.query.id) {
      this.disableds = true;
      // 调接口
      axios
        .post("api/mall/getInstockInfo", { id: this.$route.query.id })
        .then((res) => {
          console.log("sajdflk");
          console.log(res);
          this.formInline = res.data.data;
          this.formInline.channelName = res.data.data.channelUid;
          this.formInline.oemUid = localStorage.getItem("uid");
          // this.formInline.productUid = "13546733429175951378"

          // alert(this.formInline.channelName)
          // alert(this.formInline.oemUid)
          // alert(this.formInline.channelType)
          this.shopType = res.data.data.productNo;
          this.productList();
          this.formInline = res.data.data;
        })
        .catch((err) => {
          console.log(err);
        });
    }
    this.queryChannelNameList();
    https.mallCommodity({ oemUid: this.formInline.oemUid }).then((res) => {
      if (res.data.code == "0000") {
        this.options = res.data.data;
      } else {
        layer.open({
          content: d.data.msg,
          skin: "msg",
          time: 2, //2秒后自动关闭
        });
      }
    });
  },
  methods: {
    // 商品发生改变
    shoopChange(val) {
      for (let i = 0; i < this.productListData.length; i++) {
        if (this.formInline.productUid == this.productListData[i].productUid) {
          this.shopType = this.productListData[i].productNo;
        }
      }
    },
    handleClosep() {
      this.dialogVisible4 = false;
    },
    //   预览
    seeSucs() {
      this.dialogVisible4 = true;
    },
    //新增产品校验 提交
    fromData() {
      if (this.formInline.productUid == "")
        return layer.open({
          content: "商品名称不能未空",
          skin: "msg",
          time: 2,
        });
      else {
        if (this.radio == 1) {
          this.preview(1);
        }

        setTimeout(() => {
          if (this.totalNumber == "") {
            this.formInline.channelUid = this.formInline.BrandType;
            this.formInline.oemUid = localStorage.getItem("uid");
            this.disabled = true;
            https.mallSave(this.formInline).then((res) => {
              if (res.data.code !== "0000") {
                this.disabled = false;
                return layer.open({
                  content: res.data.msg,
                  skin: "msg",
                  time: 2,
                });
              }
              this.$router.push("InventoryList");
              this.disabled = false;
              return layer.open({
                content: res.data.msg,
                skin: "msg",
                time: 2,
              });
            });
          } else {
            this.formInline.channelUid = this.formInline.BrandType;
            this.formInline.oemUid = localStorage.getItem("uid");
            this.disabled = true;
            https.exprotSnConfirm(this.formInline).then((res) => {
              if (res.data.code == "0000") {
                this.$router.push("InventoryList");
                this.disabled = false;
                return layer.open({
                  content: res.data.msg,
                  skin: "msg",
                  time: 2,
                });
              } else {
                layer.open({
                  content: res.data.msg,
                  skin: "msg",
                  time: 2,
                });
                this.disabled = false;
              }
            });
          }
        }, 500);
      }
    },
    // 导入
    submitFileSave(file) {
      this.fileData = new FormData();
      this.dialogVisible1 = true;
      let that = this;
      that.fileData.append("file", file.file),
        that.fileData.append("productUid", that.formInline.productUid),
        console.log(that.fileData);
      // that.fileData.productUid=that.formInline.productUid
      https.exprotSN(that.fileData).then((res) => {
        this.fileData.delete("file");
        if (res.data.code == "0000") {
          this.dialogVisible1 = false;
          this.finalNumber = res.data.finalNumber;
          this.successNumber = res.data.successNumber;
          this.totalNumber = res.data.totalNumber;
          this.dialogVisible2 = true;
          this.disableds = true;
          this.radioBool = true;
          console.log(res);
          let successArr = [];
          let failArr = [];
          this.resSuccess = res.data.finalSNList;
          this.resFail = res.data.failList;

          // 组合成功的数据
          // for(let i =0; i<resSuccess.length;i++){
          //   successArr.push(
          //     {name:resSuccess[i],status:0}
          //   )
          // }
          // // 组合失败的数据
          // for(let i=0; i<resFail.length;i++){
          //   failArr.push({
          //     name:resFail[i],status:1
          //   })
          // }
          // console.log("成功的")
          // console.log(successArr)
          // console.log("失败的")
          // console.log(failArr)
          // // 合并数组
          // this.tableData = successArr.concat(failArr)
          console.log("合并以后的数组");
          console.log(this.tableData);
          this.uploadBool = true;
          //   这里上传成功有个预览
          return layer.open({
            content: "上传成功",
            skin: "msg",
            time: 2,
          });
        } else {
          this.fileData.delete("file");
          this.dialogVisible1 = false;
          return layer.open({
            content: res.data.msg,
            skin: "msg",
            time: 2,
          });
        }
      });
    },
    // 图片上传校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "application/vnd.ms-excel";
      if (!isJPG) {
        layer.open({
          content: "导入数据文件格式只能是 xls、xlsx 格式!",
          skin: "msg",
          time: 2,
        });
        return false;
      } else if (this.formInline.channelName == "") {
        layer.open({
          content: "品牌名称不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else if (this.formInline.channelType == "") {
        layer.open({
          content: "商品类型不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else if (this.formInline.productUid == "") {
        layer.open({
          content: "商品名称不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else {
        return isJPG;
      }
    },
    // 下载模板
    excal() {
      let that = this;
      if (that.formInline.channelName == "") {
        layer.open({
          content: "品牌名称不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else if (that.formInline.channelType == "") {
        layer.open({
          content: "商品类型不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else if (that.formInline.productUid == "") {
        layer.open({
          content: "商品名称不能为空",
          skin: "msg",
          time: 2,
        });
        return false;
      } else {
        that
          .axios({
            method: "POST",
            url: "api/mall/excel/download",
            headers: { "Content-Type": "application/json;charset=utf-8" },
            responseType: "arraybuffer",
            data: { productUid: that.formInline.productUid },
          })
          .then((res) => {
            let blob = new Blob([res.data], {
              type: "application/vnd.ms-excel;charset=utf-8",
            });
            var link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = "入库模板";
            link.click();
            that.disableds = true;
          })
          .catch((e) => {
            return layer.open({
              content: "下载失败",
              skin: "msg",
              time: 2,
            });
          });
      }
    },
    // 关闭对话框
    handleClose(n) {
      this.dialogVisible = false;
    },

    // 预览
    preview(n) {
      this.zeroNum = "";
      let regs = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (this.formInline.startSn != "") {
        // if (regs.test(this.formInline.startSn)) {
        //   return layer.open({
        //     content: "起始号段请输入字母开头加数字,或者纯数字",
        //     skin: "msg",
        //     time: 2,
        //   });
        // }
        let reg = /^[a-zA-Z][A-Za-z0-9]+|[0-9]$/;
        if (reg.test(this.formInline.startSn) === false) {
          this.previewType = false;
          return layer.open({
            content: "起始号段请输入字母开头加数字,或者纯数字",
            skin: "msg",
            time: 2,
          });
        }
        if (+this.formInline.snNum === 0) {
          this.previewType = false;
          return layer.open({
            content: "新增数量请输入纯数字",
            skin: "msg",
            time: 2,
          });
        }
      }
      for (var l = this.formInline.startSn.length - 1; l > -1; l--) {
        if (this.formInline.startSn[l] != Number(this.formInline.startSn[l])) {
          this.index = l + 1;
          break;
        }
      }
      if (this.index) {
        var englishStr = this.formInline.startSn.substring(0, this.index);
      } else {
        var englishStr = "";
      }
      this.formInline.sns = [];
      var nums = "";
      if (Number(this.formInline.startSn) == Number(this.formInline.startSn)) {
        nums = this.formInline.startSn.replace(/[^0-9]/gi, "");
      } else {
        if (/[a-zA-Z]+([0-9]+)$/.test(this.formInline.startSn)) {
          nums = RegExp.$1;
        }
      }
      // 这个nums是截取出来纯数字
      // alert("截取的数字");
      // alert(nums);
      // 如果等于0的话就循环他的所有 0
      if (nums[0] == 0) {
        for (let i = 0; i < nums.length - 1; i++) {
          if (nums[i] == 0) {
            this.zeroNum += "0";
          } else {
            break;
          }
        }
      }
      let pl;
      // alert("da" + lastNumZero)
      // 这个是取出来的数字前面的 0
      // alert(this.zeroNum)
      for (let i = 0; i < +this.formInline.snNum; i++) {
        var num = JSON.stringify(i);
        // 家出来的
        var sum = sumBigNumber(nums, num);
        let numsLength = nums.length;
        // 获取出加完毕数字的长度
        let sumLength = sum.length;
        // 截取截取的字符串的前 sumLength位
        let a = nums.substring(0, numsLength - sumLength);
        // console.log(a+sum)
        let b = a + sum;
        // 一会儿放开

        if (nums[0] == 0) {
          pl = { sn: `${englishStr}${b}` };
        } else {
          pl = { sn: `${englishStr}${sum}` };
        }
        this.formInline.sns.push(pl);
      }
      this.previewType = true;
      n !== 1 && (this.dialogVisible = true);
    },

    // 品牌名称下拉框
    queryChannelNameList() {
      let data = {
        oemUid: localStorage.getItem("uid"),
      };
      https.queryChannelNameList(data).then((res) => {
        if (res.data.code !== "0000") {
          return layer.open({
            content: res.data.msg,
            skin: "msg",
            time: 2,
          });
        }
        this.NameList = res.data.data;
      });
    },

    // 商品类型下拉框
    productList() {
      // this.formInline.productUid = "";
      this.productListData = [];
      https
        .mallProductById({
          brandChannelId: this.formInline.channelName,
          oemUid: this.formInline.oemUid,
          brandChannelTypeCode: this.formInline.channelType,
        })
        .then((res) => {
          if (res.data.code !== "0000") {
            return layer.open({
              content: res.data.msg,
              skin: "msg",
              time: 2,
            });
          }
          console.log("这里是所有商品类型");
          console.log(res);
          this.productListData = res.data.data;
        });
    },

    //点击取消
    handleCloses(done) {
      this.formInline = {
        channelUid: "",
        BrandType: "",
        productUid: "",
        saleMaxCnt: "",
        saleMinCnt: "",
        startSn: "",
        snNum: "",
        sns: [],
      };
      this.$router.push("InventoryLists");
    },
  },
};
</script>
<style scoped>
.con {
  position: relative;
}
.borderBox{
  border-right: 1px solid #ebeef5;
}
.statusBox {
  display: flex;
  border: 1px solid #ebeef5;
}
.statusBox > div {
  flex: 1;
  /* width: 50%; */
  /* border: 1px solid #ccc; */
}
.statusName {
  text-align: center;
}
.sousuojg6_10 {
  margin-top: 0;
  padding-top: 0;
}
.contbox6_10 {
  width: 100%;
  overflow-x: auto;
  box-sizing: border-box;
  float: left;
}
.statusBox {
  max-height: 200px;
  overflow-y: auto;
}
.statusList {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  text-align: center;
}
.btnExport {
  float: left;
  margin-top: 10px;
  margin-bottom: 10px;
}
.pagination {
  margin-top: 10px;
}
.shopList {
  width: 100%;
  line-height: 50px;
  font-size: 16px;
  height: 30px;
  margin-bottom: 30px;
}
.el-dialog {
  width: 25%;
}
.jibenInfo {
  width: calc(100% - 40px);
  margin: 20px;
  height: 40px;
  line-height: 40px;
  padding: 0 20px 20px;
  background: #f9fafc;
  float: left;
}
/deep/ .el-select > .el-input {
  width: 300px;
}
/deep/ .el-input__inner {
  width: 300px;
}
/deep/ .el-input {
  width: 300px;
}
/deep/ .el-cascader {
  line-height: 32px;
}
/deep/ .xuelie .el-dialog {
  height: 400px !important;
}
</style>
